package com.alu4r.atcrowdfunding.listener;

import com.alu4r.atcrowdfunding.bean.Permission;
import com.alu4r.atcrowdfunding.bean.User;
import com.alu4r.atcrowdfunding.manager.dao.UserMapper;
import com.alu4r.atcrowdfunding.manager.service.PermissionService;
import com.alu4r.atcrowdfunding.manager.service.UserService;
import com.alu4r.atcrowdfunding.util.Constant;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StartSystemListener implements ServletContextListener {
    //在服务器启动时创建Application对象时需要执行的方法
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //将项目的上下文路劲放置到application中
        ServletContext servletContext = servletContextEvent.getServletContext();
        String contextPath = servletContext.getContextPath();
        servletContext.setAttribute("APP_PATH", contextPath);


        //加载所有的许可路径
        ApplicationContext ioc = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        PermissionService permissionService = ioc.getBean(PermissionService.class);

        List<Permission> queryAllPermission = permissionService.queryAllPermission();

        Set<String> allURIs = new HashSet<>();
        for (Permission permission : queryAllPermission) {
            allURIs.add("/" + permission.getUrl());
        }
        servletContext.setAttribute(Constant.ALL_PERMISSION_URI, allURIs);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
